<template>
  <view class="container page-with-cunba-nav">
    <!-- 页面内容 -->
    <view class="page-content" :style="navBarStyle">
      <!-- 民宿导航栏组件 -->
      <house-nav-bar 
        @nav-height="onNavHeightChange"
        @city-changed="onCityChanged"
        @go-back="handleBack"
      />
      
      <!-- 标题区域 -->
      <view class="header-section">
        <view class="main-title">{{ eventInfo.name }}</view>
        <view class="sub-title" v-html="formatSubtitle(eventInfo.subtitle)"></view>        
      </view>

      <!-- 选项卡 -->
      <view class="tab-section" v-if="groupList.length > 0">
      <view 
        class="tab-item" 
        v-for="(group, index) in groupList" 
          :key="group.id"
          :class="{ active: activeGroupIndex === index }"
          @click="switchTab(index)"
        >
          {{ group.name }}
        </view>
        </view>
      
      <!-- 无组别数据时的占位 -->
      <view class="tab-section tab-placeholder" v-else-if="!loading">
        <view class="tab-item placeholder">
          {{ displayCityName }}暂无比赛数据
        </view>
      </view>
      
      <!-- 加载中的占位 -->
      <view class="tab-section tab-placeholder" v-else>
        <view class="tab-item placeholder">
          组别加载中...
        </view>
      </view>
      
      <!-- 排行榜表格组件 -->
      <RankingTable 
        :teamList="currentTeamList"
        :loading="loading"
        :emptyText="getEmptyStateText()"
        :emptyTips="getEmptyStateTips()"
        @team-click="goToTeamDetail"
      />
    </view>
    
    <!-- 自定义导航栏 -->
    <cunba-nav-bar :activeIndex="2" @nav-change="onNavChange"></cunba-nav-bar>
  </view>
</template>

<script>
import CunbaNavBar from '@/components/cunba-nav-bar/index.vue'
import HouseNavBar from '@/components/house_nav/index.vue'
import RankingTable from '@/components/cunba/RankingTable/index.vue'
import { getTeamRanking } from '@/api/cunba.js'

export default {
  components: {
    CunbaNavBar,
    HouseNavBar,
    RankingTable
  },
  data() {
    return {
      currentTab: '', // 当前选中的选项卡（动态设置）
      teamData: {}, // 清空模拟数据，等待真实数据
      loading: false, // 加载状态
      // 赛事信息
      eventInfo: {
        name: '排行榜', // 默认标题
        subtitle: '赛事数据加载中...' // 默认副标题
      },
      // 组别列表
      groupList: [],
      // 当前选中的组别索引
      activeGroupIndex: 0,
      // 排行榜数据
      rankingData: [], // 存储所有排名数据
      currentGroupTeams: [], // 当前组别的球队数据
  
    }
  },
  computed: {
    // 导航栏样式计算属性
    navBarStyle() {
      const paddingValue = Math.max(this.navBarHeight + 20, 108);
      return {
        '--nav-bar-padding': `${paddingValue}px`
      };
    },
    // 当前选项卡对应的球队列表
    currentTeamList() {
      console.log('=== 排行榜页面 currentTeamList 计算 ===')
      console.log('currentGroupTeams:', this.currentGroupTeams)
      console.log('currentGroupTeams长度:', this.currentGroupTeams.length)
      
      // 过滤掉无效数据并添加防护
      const validTeams = this.currentGroupTeams.filter(team => {
        const isValid = team && typeof team === 'object'
        if (!isValid) {
          console.warn('⚠️ 排行榜页面 - 过滤掉无效球队数据:', team)
        }
        return isValid
      })
      
      console.log('过滤后的有效球队数据:', validTeams)
      return validTeams
    },
    // 当前选中的组别信息
    currentGroup() {
      return this.groupList[this.activeGroupIndex] || null
    },
    
    // 显示的城市名称
    displayCityName() {
      const savedLocation = this.$store.state.location || this.$store.getters.getLocation
      return (savedLocation && savedLocation.address) || '当前位置'
    }
  },
  onLoad() {
    // 设置初始导航栏标题
    uni.setNavigationBarTitle({
      title: this.eventInfo.name
    })
    
    // 延迟加载数据，等待导航栏组件初始化完成
    this.$nextTick(() => {
      setTimeout(() => {
        this.loadRankingData()
      }, 500)
    })
  },
  onShow() {
    // 页面显示时可以刷新数据
  },

  /**
   * 处理导航栏返回按钮点击事件
   */
  onNavigationBarButtonTap() {
    uni.navigateBack({
      delta: 1
    })
  },
  methods: {
    // 导航栏高度变化回调
    onNavHeightChange(height) {
      this.navBarHeight = height
    },
    
    // 城市切换回调
    onCityChanged(data) {
      console.log('城市已切换:', data)
      // 重新加载排行榜数据
      this.loadRankingData()
    },
    
    // 返回按钮回调
    handleBack() {
      console.log('村BA排行榜页面返回按钮点击');
      // HouseNavBar组件已经处理了返回逻辑，这里不需要额外处理
    },
    // 切换选项卡
    switchTab(index) {
      this.activeGroupIndex = index
      const selectedGroup = this.groupList[index]
      if (selectedGroup) {
        this.currentTab = selectedGroup.id || selectedGroup.name
        console.log('切换到组别:', selectedGroup.name, '索引:', index)
        // 切换组别时筛选对应的球队数据
        this.filterGroupData(selectedGroup)
      }
    },
    // 加载排行榜数据
    async loadRankingData() {
      console.log('=== 开始加载排行榜数据 ===')
      this.loading = true
      
      try {
        // 测试参数 - 根据文档使用示例参数
        const testParams = [
          { eventId: 2, groupId: 1, matchType: 'group' },
          { eventId: 2, groupId: 4, matchType: 'final' },
          { eventId: 2, groupId: 2, matchType: 'group' },
          { eventId: 2, groupId: 3, matchType: 'group' }
        ]
        
        // 从store获取城市参数
        const savedLocation = this.$store.state.location || this.$store.getters.getLocation
        if (savedLocation && (savedLocation.city || savedLocation.province)) {
          const cityName = savedLocation.city || savedLocation.province
          if (cityName && cityName !== '当前位置') {
            testParams.forEach(param => {
              param.city = cityName
            })
            console.log('=== 添加城市参数 ===')
            console.log('城市参数:', cityName)
          }
        }
        
        for (let i = 0; i < testParams.length; i++) {
          const params = testParams[i]
          console.log(`\n--- 请求 ${i + 1}: 参数 ---`)
          console.log('请求参数:', params)
          
          try {
            const response = await getTeamRanking(params)
            console.log(`--- 请求 ${i + 1}: 响应成功 ---`)
            console.log('完整响应:', response)
            
            // 处理API响应
            if (response && response.code === 0 && response.data) {
              console.log('--- 解析后的数据结构 ---')
              console.log('赛事信息:', response.data.event)
              console.log('组别列表:', response.data.groups)
              console.log('当前组别:', response.data.currentGroup)
              console.log('排名数据:', response.data.rankings)
              console.log('排名数据长度:', response.data.rankings ? response.data.rankings.length : 0)
              
              // 更新标题信息和组别信息（使用第一次成功请求的数据）
              if (i === 0) {
                // 更新标题
                if (response.data.event) {
                  this.eventInfo.name = response.data.event.name || '排行榜'
                  this.eventInfo.subtitle = response.data.event.subtitle || '比赛进行中'
                  
                  // 更新系统导航栏标题
                  uni.setNavigationBarTitle({
                    title: this.eventInfo.name
                  })
                  
                  console.log('--- 更新页面标题 ---')
                  console.log('主标题:', this.eventInfo.name)
                  console.log('副标题:', this.eventInfo.subtitle)
                }
                
                // 更新组别列表
                if (response.data.groups && response.data.groups.length > 0) {
                  this.groupList = response.data.groups
                  this.activeGroupIndex = 0
                  this.currentTab = this.groupList[0].id || this.groupList[0].name
                  console.log('--- 更新组别列表 ---')
                  console.log('组别列表:', this.groupList)
                  console.log('默认选中组别:', this.groupList[0].name)
                }
                
                // 更新排行榜数据
                if (response.data.rankings && response.data.rankings.length > 0) {
                  this.rankingData = response.data.rankings
                  console.log('--- 更新排行榜数据 ---')
                  console.log('排行榜数据:', this.rankingData)
                  console.log('排行榜数据长度:', this.rankingData.length)
                  
                  // 如果有组别数据，筛选默认组别的球队数据
                  if (this.groupList.length > 0) {
                    this.filterGroupData(this.groupList[0])
                  }
                } else {
                  // 没有排名数据时清空列表
                  console.log('--- 没有排名数据，清空列表 ---')
                  this.rankingData = []
                  this.currentGroupTeams = []
                }
              }
              
              // 详细打印第一个队伍数据
              if (response.data.rankings && response.data.rankings.length > 0) {
                console.log('--- 第一个队伍详细信息 ---')
                console.log('队伍数据:', response.data.rankings[0])
              }
            } else if (response && response.code === 400) {
              // 处理"暂无排名数据"的情况
              console.log('--- API返回暂无数据 ---')
              console.log('响应信息:', response.msg || '暂无排名数据')
              
              // 清空排名数据，但保留其他信息
              if (i === 0) {
                this.rankingData = []
                this.currentGroupTeams = []
                console.log('--- 清空排名数据 ---')
              }
            }
          } catch (error) {
            console.log(`--- 请求 ${i + 1}: 请求失败 ---`)
            console.error('请求错误:', error)
            console.error('错误详情:', {
              message: error.message,
              code: error.code,
              config: error.config
            })
          }
          
          // 延迟一秒再请求下一个，避免请求过快
          if (i < testParams.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 1000))
          }
        }
        
        console.log('\n=== 排行榜数据加载完成 ===')
        
      } catch (error) {
        console.error('=== 数据加载过程出错 ===')
        console.error('错误:', error)
        uni.showToast({
          title: '数据加载失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
      }
    },
    // 筛选组别数据
    filterGroupData(group) {
      console.log('=== 筛选组别数据 ===')
      console.log('当前组别:', group)
      console.log('总排行榜数据长度:', this.rankingData.length)
      console.log('总排行榜数据:', this.rankingData)
      
      if (!group || !this.rankingData.length) {
        console.log('⚠️ 组别或排行榜数据为空，设置空数组')
        this.currentGroupTeams = []
        return
      }
      
      // 根据组别名称筛选对应的球队数据
      const filteredTeams = this.rankingData.filter(team => {
        const match = team.group === group.name || team.groupName === group.name
        console.log(`球队 ${team.teamName || team.name} (组别: ${team.group || team.groupName}) 是否匹配组别 ${group.name}:`, match)
        return match
      })
      
      console.log('筛选后的球队数据:', filteredTeams)
      
      // 按排名排序
      this.currentGroupTeams = filteredTeams.sort((a, b) => {
        const rankA = a.rank || 999
        const rankB = b.rank || 999
        return rankA - rankB
      })
      
      console.log(`=== 组别 ${group.name} 最终球队数据 ===`)
      console.log('currentGroupTeams长度:', this.currentGroupTeams.length)
      console.log('currentGroupTeams详情:', this.currentGroupTeams)
      
      // 检查每个球队的ID字段
      this.currentGroupTeams.forEach((team, index) => {
        console.log(`球队${index + 1}:`, {
          id: team.id,
          teamId: team.teamId,
          name: team.name,
          teamName: team.teamName,
          originalData: team
        })
      })
    },

    // 跳转到球队详情页面
    goToTeamDetail(team) {
      console.log('=== 点击球队跳转详情页 ===')
      console.log('接收到的team参数:', team)
      console.log('team类型:', typeof team)
      
      // 参数有效性检查
      if (!team || typeof team !== 'object') {
        console.warn('⚠️ 球队数据无效:', team, '使用默认数据')
        team = { id: 3, name: 'BSK' }
      }
      
      try {
        const teamId = team.teamId || team.id || 3
        const teamName = team.teamName || team.name || 'BSK'
        const eventId = 2
        
        const url = `/pages/cunba/team_detail/index?teamId=${teamId}&teamName=${encodeURIComponent(teamName)}&eventId=${eventId}`
        console.log('跳转到球队详情:', { teamId, teamName, eventId })
        
        uni.navigateTo({ 
          url,
          success: () => {
            console.log('✅ 球队详情跳转成功')
          },
          fail: (err) => {
            console.error('❌ 球队详情跳转失败:', err)
            uni.showToast({
              title: '页面跳转失败，请重试',
              icon: 'error'
            })
          }
        })
      } catch (error) {
        console.error('❌ 球队详情跳转过程出错:', error)
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'error'
        })
      }
    },
    
    // 自定义导航栏切换事件
    onNavChange(navData) {
      // 处理导航栏切换逻辑
    },
    // 格式化副标题，支持换行符
    formatSubtitle(subtitle) {
      if (!subtitle) return ''
      return subtitle.replace(/\n/g, '<br>')
    },
    
    
    // 获取空状态文本
    getEmptyStateText() {
      const savedLocation = this.$store.state.location || this.$store.getters.getLocation
      const cityName = (savedLocation && savedLocation.address) || '当前位置'
      if (this.currentGroup) {
        return `${cityName}暂无${this.currentGroup.name}排名数据`;
      }
      return `${cityName}暂无排名数据`;
    },
    
    // 获取空状态提示
    getEmptyStateTips() {
      const savedLocation = this.$store.state.location || this.$store.getters.getLocation
      const cityName = (savedLocation && savedLocation.address) || '当前位置'
      if (cityName === '当前位置') {
        return '请选择城市查看排名数据';
      }
      return '请尝试选择其他城市';
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.page-content {
  padding: 20px;
  /* 确保页面内容不被固定定位的导航栏遮挡 */
  padding-top: 120px;
}

/* 标题区域 */
.header-section {
  text-align: center;
  margin-bottom: 30px;
    
    .main-title {
      font-size: 28px;
      font-weight: bold;
    color: #fff;
    margin-bottom: 10px;
    }
    
    .sub-title {
    font-size: 14px;
      color: rgba(255, 255, 255, 0.9);
    line-height: 1.4;
  }
}

/* 选项卡区域 */
.tab-section {
  display: flex;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 25px;
  padding: 4px;
  margin-bottom: 20px;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 10px 0;
    border-radius: 20px;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.7);
    transition: all 0.3s ease;
    cursor: pointer;
    
    &.active {
      background: #ff6b35;
        color: #fff;
        font-weight: bold;
      }
    
    &.placeholder {
      color: rgba(255, 255, 255, 0.5);
      cursor: default;
      font-style: italic;
    }
  }
}



/* 页面容器样式 */
.page-with-cunba-nav {
  padding-bottom: calc(80px + env(safe-area-inset-bottom));
}

/* 禁用页面过渡动画 */
// #ifdef H5
.uni-page {
  transition: none !important;
  animation: none !important;
}
// #endif
</style>
